package com.su.gulimall.order.web;

import com.su.gulimall.order.exception.NoStockException;
import com.su.gulimall.order.service.OrderService;
import com.su.gulimall.order.vo.OrderConfirmVo;
import com.su.gulimall.order.vo.OrderSubmitVo;
import com.su.gulimall.order.vo.SubmitOrderResp;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpRequest request) throws ExecutionException, InterruptedException {
        //展示订单的数据
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmVo", orderConfirmVo);
        return "confirm";
    }

    @PostMapping("/submit")
    public String submit(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes attributes) {
        //下单：创建订单，验令牌，验价格，锁库存；
        //下单成功；回到支付选择页
        //下单失败：回到订单确认页
        SubmitOrderResp submitOrder = null;
        try {
            //下单成功
            submitOrder = orderService.submitOrder(orderSubmitVo);
            model.addAttribute("submitOrderResp", submitOrder);
            return "pay";
        } catch (Exception e) {
            //下单失败的处理
            if(e instanceof NoStockException)
            {
                String message=((NoStockException)e).getMessage();
                attributes.addFlashAttribute("msg","下单失败"+message);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
        }


}